// pages/goods/goods.js
timer = require('../../utils/wxTimer.js')
var app = getApp().globalData,
timer = app.timer;
Page({
    data: {
        Token:'',               // 用户登陆标识:
        cid:0,                  // 商品id
        upid:0,                 // 分享过来的上级ID
        mid:0,                  // 秒杀商品id
        CommodityInfo:[],       // 商品详细信息信息
        ShopInfo:[], // 店铺信息
        TypeInfo:[], // 商品类型信息
        SellerInfo:[],          //商家信息
        PingInfo:[],            //评论信息
        // 秒杀信息
        KillInfo:{},
        MaxNum:100000,          //限购数量
        EndTime:'00:00:01',             //活动开始或结束时间  
        TimeArea:'start',       //start 则渲染距离互动开始，middle 则渲染距离活动结束  stop 渲染活动已结束          
        // 防暴力滑块
        minusStatus: 'disabled',
        isFlag:false,
        radio3:3,
        // 订单信息
        Order:{
            Num:1,
        },
        uid:0,// 分享框
        dialogVisible:false,
        CopyText:'',// 规格
        radio:'1',// 订单弹窗
        iFname:false,
        UserPay:'',// 支付密码
        PayWord:'',
        Show:0,             //显示选项卡信息
        // 倒计时组件区
        wxTimer:'',
        wxTimerSecond:'',
        wxTimerList:{},
        red:'red'       // 变色

    },
    // 滑块组件
    verifyResult(){
        this.setData({
            isFlag:true
        })
    },
    // 选项卡组件
    TabFun(e){
        console.log(e.detail);
        this.setData({
            Show:e.detail
        })
    }, 
    // 判断用户是否登陆
    TestLogin(){
        // 判断是否登陆了
        if(!this.data.Token){
            this.Alert('提示','您尚未登陆或账号异常，请重新登陆再操作该商品~');
            return false;
        }else{
            return true;
        };
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
		let cid = options.cid ? options.cid : 0;
		let mid = options.mid ? options.mid : 0;
		this.setData({
			cid:cid,
			mid:mid,
			// Token:'a346a4c43d3ebda505ae2427a153fca5',
        });
        console.log(this.data.mid);
        console.log(this.data.cid);
        
	
        var that = this;
        wx.getStorage({
            key: 'token',
            success (res) {
				
                that.setData({
                    Token:res.data
                });
            }
        });
        this.GetCommodityInfo(); 
    },


    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },
    // 运行计时器
    RunTimer(now){
        var that = now;
        var wxTimer = new timer({
            beginTime: that.data.EndTime,
            complete:function(){
                that.TimeFunction(that);
            },
        })
        wxTimer.start(that);
    },
    TimeFunction(NOW){
        var that = NOW;
        switch(true){
            case that.data.TimeArea=='start':
                var ActTime = that.TimeChuo(that.data.KillInfo.kill_stop_time);
                that.setData({
                    EndTime : that.TimeZhuan(ActTime - new Date().getTime()),
                    TimeArea:'middle',
                });
                that.Alert('提示：','活动已经开始，请抓紧机会呦！');
            break;
            case that.data.TimeArea=='middle'||that.data.TimeArea=='stop':
                that.setData({
                    EndTime : '00:00:01',
                    TimeArea:'stop',
                });
                that.Alert('提示：','活动已经结束，可以去参加其他时段的秒杀活动！');
            break;
        };
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },
    /* 点击减号 */  
    bindMinus: function() {  
        var num = this.data.Order.Num;  
        // 如果大于1时，才可以减  
        if (num > 1) {  
            num --;  
        }  
        // 只有大于一件的时候，才能normal状态，否则disable状态  
        var minusStatus = num <= 1 ? 'disabled' : 'normal';  
        // 将数值与状态写回  
        this.setData({  
            ['Order.Num']:num, 
            minusStatus: minusStatus  
        });   
    },  
    /* 点击加号 */  
    bindPlus: function() {  
        var num = this.data.Order.Num;
        // 不作过多考虑自增1  
        num ++;  
        // 只有大于一件的时候，才能normal状态，否则disable状态  
        var minusStatus = num < 1 ? 'disabled' : 'normal';  
        // 将数值与状态写回  
        this.setData({  
            ['Order.Num']:num,
            minusStatus:minusStatus  
        });    
    },  
    /* 输入框事件 */  
    bindManual: function(e) {  
        var num = e.detail.value;  
        // 将数值与状态写回  
        this.setData({  
            ['Order.Num']:num,
        });  
    },
    // 请求商品相关信息  
    GetCommodityInfo:function(){
        var that = this;
        wx.request({
            url: 'http://47.104.142.216/TP/public/index.php/index/Goods/GetCommodity',
            dataType:'json',
            data:{
                cid:this.data.cid,
                mid:this.data.mid,
            },
            method:'POST',
            header:{
              'content-type':'application/x-www-form-urlencoded'
            },
            success:function(res){
               // console.log(res.data);
                
                switch(true){
                    case res.data.ErrorCode==1:
                        let comInfo = res.data.data.comdata
                        // 生成规格数组
                        let Mold = comInfo.commodity_text.split(',');
                        that.setData({  
                            CommodityInfo:comInfo,
                            PingInfo:res.data.data.pingdata,
                            // 添加到信息对象中
                            ['CommodityInfo.Mold']:Mold,
                            // 设置默认规格
                            radio:Mold[0],
                            ['Order.Mold']:Mold[0],
                            // 保存商铺信息
                            ShopInfo : res.data.data.shopdata,
                            // 保存商家信息
                            SellerInfo : res.data.data.sellerdata,
                            // 秒杀信息
                            KillInfo : res.data.data.killdata,
                        }); 

                        if(that.data.KillInfo.k_id){
                            that.setData({
                                ['CommodityInfo.commodity_price']:that.data.KillInfo.kill_com_price,
                                MaxNum:that.data.KillInfo.kill_com_quota,
                            })
                            // 判断秒杀活动倒计时
                            var NowTime = new Date().getHours();
                            switch(true){
                                case NowTime<that.data.KillInfo.kill_start_time:
                                    var ActTime = that.TimeChuo(that.data.KillInfo.kill_start_time);
                                    var ChaTime = ActTime - new Date().getTime();
                                    that.setData({
                                        EndTime:that.TimeZhuan(ChaTime),
                                        TimeArea:'start',
                                    });
                                break;
                                case NowTime<that.data.KillInfo.kill_stop_time:
                                    var ActTime = that.TimeChuo(that.data.KillInfo.kill_stop_time);
                                    var ChaTime = ActTime - new Date().getTime();
                                    that.setData({
                                        EndTime:that.TimeZhuan(ChaTime),
                                        TimeArea:'middle',
                                    });
                                break;
                                case NowTime>that.data.KillInfo.kill_stop_time:
                                    that.setData({
                                        EndTime:'00:00:01',
                                        TimeArea:'stop',
                                    });
                                break;
                            }
                           // console.log(that.data.EndTime);
                            
                            that.RunTimer(that);
                        };
                        // 保存类型信息
                        that.setData({
                            TypeInfo:res.data.data.typedata[0]
                        });
                    break;
                    case res.data.ErrorCode==0:
                        that.Alert('信息查找','失败');
                    break;
                }
            }
        })
    },
    // 获取今天某小时的时间戳
    TimeChuo(hour){
        var date = new Date();
        date.setDate(date.getDate());
        date.setHours(hour);
        date.setMinutes(0);
        date.setSeconds(0);
        var Alltime = date.getTime();
        return Alltime;
    },
    // 时间戳转成时分秒(补零)
    TimeZhuan(mss){
        var hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = parseInt((mss % (1000 * 60)) / 1000);
        hours = hours < 10 ? ('0' + hours) : hours;
        minutes = minutes < 10 ? ('0' + minutes) : minutes;
        seconds = seconds < 10 && seconds >= 1 ? ('0' + seconds) : seconds;
        return  hours + ":" + minutes + ":" + seconds;
    },
    // 选择商品规格
    MoldChoic(e){
        let res = e.currentTarget.dataset.value;
        this.setData({
            radio:res,
            ['Order.Mold']:res,
        });
    },
    // 封装弹窗
    Alert(title='提示',text){
        wx.showModal({
            title: title,
            content: text,
            success (res) {
              if (res.confirm) {
                // console.log('用户点击确定')
              } else if (res.cancel) {
                // console.log('用户点击取消')
              }
            }
          })
	},
	Message(title,success){
		wx.showToast({
			title: title,
			icon: success,
			duration: 2000
		})
    },
    // 加入购物车---->秒杀订单不支持加入购物车
    ShopCar(){
        // 判断是否登陆
        if(!this.TestLogin()){
            return false;
		};
		let that = this;
		wx.request({
		  url: 'http://47.104.142.216/TP/public/index.php/index/Goods/PushCar',
		  data:{
			cid:that.data.CommodityInfo.commodity_id,
            mold:that.data.Order.Mold,
            token:that.data.Token,
            num:that.data.Order.Num,
            type:1,
		  },
		  dataType:'json',
		  method:"POST",
		  success:function(res){
			switch(true){
                case res.data.ErrorCode==1:
                    that.Alert('提示','该商品已加入购物车,请至个人中心查看');
                break;
                case res.data.ErrorCode==0:
                    that.Alert('提示','信息查找,失败');
				break;
				case res.data.ErrorCode==10086:
					that.Alert('警告：',res.data.msg);
				break;
				case res.data.ErrorCode==10087:
					that.Alert('警告：',res.data.msg);
				break;
            }
		  },
		})
    },
    // 立即购买---->生成订单信息
    BuyNow(){
		var that = this;
        // 判断是否在秒杀时间内
        if(that.data.mid>0&&(that.data.TimeArea=='stop'||that.data.TimeArea=='start')){
            that.Alert('警告','现在不在秒杀活动开始的时间，请耐心等待！');
            return false;
        }

        // 判断是否进行了滑块验证
        if (!that.data.isFlag) {
            that.Alert('警告','您尚未进行防暴力购买验证，请验证后在下单');
            return false;
        };

        // 判断是否登陆
        if(!this.TestLogin()){
            return false;
        };

        // 验证成功后修改订单数据 this.Order
		// 单价
		that.setData({
			['Order.Price']:that.data.CommodityInfo.commodity_price,
			['Order.Cid']:that.data.CommodityInfo.commodity_id,
			['Order.Money']:that.data.Order.Num * that.data.CommodityInfo.commodity_price,
			['Order.Name']:that.data.CommodityInfo.commodity_name,
			iFname:true,	 // 验证支付密码，显示支付密码框
		});
	},
	cancel(){
		this.setData({
            iFname:false,
            UserPay:'',
            PayWord:'',
		});
	},
    // 立即购买---->下单
    AddOrder(now,text){
		wx.request({
		  url: 'http://47.104.142.216/TP/public/index.php/index/Goods/AddOrder',
		  data:{
			token:now.data.Token,
            upid:now.data.upid,
            mid:now.data.mid,
            order:JSON.stringify(now.data.Order),
            type:1,             //用来进行登陆验证
            status:text,
		  },
		  dataType:'json',
		  method:'POST',
		  success:function(res){
			switch(true){
                case res.data.ErrorCode == 0:
                    now.Alert('提示','下单失败');
                break;
                case res.data.ErrorCode == 1:
                    now.Alert('提示：','下单成功，请至个人中心查看订单信息');
                break;
                case res.data.ErrorCode == 2:
                    now.Alert('提示','用户余额不足，订单已保存至个人中心，请至个人中心查看并支付！');
                break;
                case res.data.ErrorCode == 3:
                    now.Alert('提示','下单失败，商品库存不足，请联系客服询问是否有余货！');
                break;
                case res.data.ErrorCode==10086:
                    now.Alert('警告：',res.data.msg);
                break;
                case res.data.ErrorCode==10087:
                    now.Alert('警告：',res.data.msg);
                break;
            };
		  },
		})
    },
    // 输入支付密码
	setValue(res){
		this.setData({
			UserPay:res.detail.value,
		})
    },
    // 
	TestPay(){
        var that = this;
        // 支付密码正则判断
        /***
         *空值判断
         */
        if(that.data.UserPay==''||that.data.UserPay==null){
            that.Alert('警告：','请输入支付密码！');
            return false;
        };
		wx.request({
		  url: 'http://47.104.142.216/TP/public/index.php/index/Goods/Test',
		  data:{
			token:this.data.Token,
            pay:this.data.UserPay,
            type:1,             //用来进行登陆验证
		  },
		  dataType:'json',
		  method:'POST',
		  success:function(res){
			if(res.data.ErrorCode==1){
				that.Message('成功','提示：支付密码输入成功，即将生成订单！');
				that.setData({
					iFname:false,
                    UserPay:'',
                    PayWord:'',
                });
				that.AddOrder(that,'yes');
            }else{
                that.Alert('错误','支付密码输入错误，请重新输入');
                that.setData({
                    UserPay:'',
                    PayWord:'',
				})
            };
		  },
		})
    },
    // 收藏按钮
    Collection(){
        var that = this;
        // 秒杀判断
        if(that.data.mid>0){
            that.Alert('提示：','该商品为特价商品，收藏的价格将与现价有所不同！');
        };

        // 判断是否登陆
        if(!that.TestLogin()){
            return false;
        };
        wx.request({
            url: 'http://47.104.142.216/TP/public/index.php/index/Goods/CollectionCommodity',
            data:{
                cid:that.data.CommodityInfo.commodity_id,
                token:that.data.Token,
                type:1,
            },
            dataType:"json",
            method:'POST',
            header:{
                'content-type':'application/x-www-form-urlencoded'
			},
			success:function(res){
				switch(true){
					case res.data.ErrorCode==0:
						that.Alert('商品收藏：','失败');
					break;
					case res.data.ErrorCode==1:
						that.Alert('提示','该商品已加入收藏夹，请至个人中心查看');
					break;
					case res.data.ErrorCode==2:
						that.Alert('警告：',res.data.msg);
					break;
					case res.data.ErrorCode==10086:
						that.Alert('警告：',res.data.msg);
					break;
					case res.data.ErrorCode==10087:
						that.Alert('警告：',res.data.msg);
					break;
				}
			},
		})
	},
	// 跳转至对应商铺
	Jump(event){
		let id = event.currentTarget.dataset.id;
		wx.redirectTo({
		  url: '../shop/shop?shopid='+id,
		})
	}
})